#include "Actor.h"

using namespace Ogre;
using namespace std;


Actor::Actor(SceneManager* sceneMgr) : GameObject(sceneMgr) {}

Actor::Actor(SceneManager* sceneMgr, String name) : GameObject(sceneMgr, name) {}

Actor::~Actor() {}

void Actor::init(Ogre::Root *root) {
	if (!root->getSceneManagerIterator().hasMoreElements())
		OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "No scene manager found!", "init");

//mSceneMgr = root->getSceneManagerIterator().getNext();
	root->addFrameListener(this);
	}

void Actor::init(Real mass) {

	try {
			BtOgre::StaticMeshToShapeConverter converter(mEntity);
			//        BtOgre::StaticMeshToShapeConverter converter();

			mCollisionShape = converter.createConvex();
			//        mCollisionShape = converter.createBox();
			//        mCollisionShape = new btBoxShape(btVector3(2,2,2));

			BtOgre::RigidBodyState *state = new BtOgre::RigidBodyState(mNode);
			//        btMotionState *state = new btDefaultMotionState();

			btVector3 inertia(0,0,0);
			if (mass!=0.0)
				mCollisionShape->calculateLocalInertia(mass, inertia);

			btRigidBody::btRigidBodyConstructionInfo rigidBodyCI(mass, state, mCollisionShape, inertia);

			mRigidBody = new btRigidBody(rigidBodyCI);
			} catch (...) {
			OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Error initiating actor!", "init");
			}
//        phyWorld->addRigidBody(mRigidBody);
	}


void Actor::setPosition(const Vector3& pos) {
	if (mNode==NULL) return;
	mNode->setPosition(pos);

	if (mRigidBody==NULL) return;

	btTransform trans;
	trans.setIdentity();
	mRigidBody->getMotionState()->getWorldTransform(trans);

	trans.setOrigin(BtOgre::Convert::toBullet(pos));

	mRigidBody->getMotionState()->setWorldTransform(trans);
	mRigidBody->setCenterOfMassTransform(trans);
	}

Vector3 Actor::getPosition() {
	btTransform trans;
	trans.setIdentity();
	mRigidBody->getMotionState()->getWorldTransform(trans);
	Vector3 v = BtOgre::Convert::toOgre(trans.getOrigin());
	return v;
	}




void Actor::yaw(const Real &angle) {
	mNode->yaw((Radian)angle);

	btTransform trans;
	mRigidBody->getMotionState()->getWorldTransform(trans);
	trans.setRotation(BtOgre::Convert::toBullet(mNode->getOrientation()));
	}
/**
* Update SceneNode with Bullet position and such
*/
bool Actor::frameStarted(const Ogre::FrameEvent &evt) {


//	btTransform trans;
//	mRigidBody->getMotionState()->getWorldTransform(trans);
//
//	mNode->setPosition(BtOgre::Convert::toOgre(trans.getOrigin()));
//	mNode->setOrientation(BtOgre::Convert::toOgre(trans.getRotation()));

	return true;
	}

/**
*/
bool Actor::frameEnded(const Ogre::FrameEvent &evt) {
	return true;
	}
